<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>水果列表</h1>
        
        <form @submit.prevent="insert">
            <input type="text" v-model="name">
            <input type="text" v-model.number="price">
            <button>添加</button>
        </form>

        <ul>
            <li v-for="item,index in list">
                名称：{{item.name}}；
                单价：{{item.price}}；
                数量
                <button @click="decrease(index)">-</button>
                <span>{{item.count}}</span>
                <button @click="increase(index)">+</button>
            </li>
        </ul>

        <h3>总价：{{totalPrice}}</h3>
    </div>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        Vue.createApp({
            data(){
               return {
                   name:"",
                   price: 0,
                   list:[]
               }
            },
            computed:{
                totalPrice(){
                    let sum = 0;
                    this.list.forEach(v => {
                        sum += (v.price*v.count);
                    })
                    return sum
                }
            },
            methods:{
                insert(){
                    this.list.push({
                        name:this.name,
                        price:this.price,
                        count:1    
                    })
                },
                increase(i){
                   this.list[i].count ++;
                },
                decrease(i){
                    /*
                        原来的代码的bug
                        confirm点击取消后仍然会执行 count --的操作
                    */
                    if(this.list[i].count ==1 
                        && confirm("是否删除？") ){
                            this.list.splice(i,1)
                    }
                    if(this.list[i].count>1){
                        this.list[i].count --;
                    }
                }

            }
        }).mount("#app")
    </script>
</body>
</html>